package com.lagou.edu.controller;

import com.lagou.edu.entity.Token;
import com.lagou.edu.service.TokenService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;
import java.util.UUID;

/**
 * @Author: yeqingyun
 * @Date: 2020/11/20 15:42
 */
@RequestMapping("/token")
@RestController
@RequiredArgsConstructor
public class TokenController {

    private final TokenService tokenService;

    @RequestMapping("/create/{email}")
    public String create(@PathVariable("email") String email) {
        String tokenStr = UUID.randomUUID().toString();
        Token token = new Token();
        token.setEmail(email);
        token.setToken(tokenStr);
        tokenService.add(token);
        return tokenStr;
    }

    @RequestMapping("/email/{token}")
    public String email(@PathVariable("token") String token) {
        Optional<Token> tokenOptional = tokenService.getByToken(token);
        if (!tokenOptional.isPresent()) {
            return "";
        }
        return tokenOptional.get().getEmail();
    }

}
